#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <filesystem>
#include <time.h>
#include "Mutex.hpp"

namespace LogModule
{

    using namespace LockModule;
    // 1、日志文件的默认路径与文件名
    const std::string defaultlogpath = "./mylog/";
    const std::string defaultlogname = "log.txt";

    std::string CurrentTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm ccur;
        localtime_r(&time_stamp, &ccur);

        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 ccur.tm_year + 1900,
                 ccur.tm_mon + 1,
                 ccur.tm_mday,
                 ccur.tm_hour,
                 ccur.tm_min,
                 ccur.tm_sec);

        return buffer;
    }

    // 2、日志等级
    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string Level_to_string(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "DEBUG";
        case LogLevel::WARNING:
            return "DEBUG";
        case LogLevel::ERROR:
            return "DEBUG";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "NONE";
        }
    }

    // 3、刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void Synclog(const std::string &message) = 0;
    };

    // 3.1、控制台策略
    class Consolelogstrtegy : public LogStrategy
    {
    public:
        Consolelogstrtegy()
        {
        }

        ~Consolelogstrtegy()
        {
        }

        void Synclog(const std::string &message)
        {
            LockGuard lockguard(_lock); // 防止多个进程打印乱码
            std::cout << message << std::endl;
        }

    private:
        Mutex _lock;
    };

    // 3.2、文件级(磁盘)策略

    class FilelogStrategy : public LogStrategy
    {
    public:
        FilelogStrategy(const std::string &logpath = defaultlogpath, const std::string &logname = defaultlogname)
            : _logname(logname),
              _logpath(logpath)
        {
            // 确认目录存在

            if (std::filesystem::exists(_logpath)) // 存在
            {
                return;
            }
            // 不存在就创建
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cout << e.what() << "\n";
            }
        }

        ~FilelogStrategy()
        {
        }

        void Synclog(const std::string &message)
        {
            std::string log = _logpath + _logname; // /mylog/log.txt
            std::ofstream out(log, std::ios::app); // 日志写入一定是追加

            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }

    private:
        std::string _logname;
        std::string _logpath;
    };

    // 日志类:构建日志字符串

    class Logger
    {
    public:
        Logger()
        {
            // 默认采用Consolelogstrtegy策略
            _strategy = std::make_shared<Consolelogstrtegy>();
        }

        void EnableConsoleLog()
        {
            _strategy = std::make_shared<Consolelogstrtegy>();
        }

        void EnableFileLog()
        {
            _strategy = std::make_shared<FilelogStrategy>();
        }
        ~Logger() {}

        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, uint32_t line, Logger &logger)
                : _current_time(CurrentTime()),
                  _level(level),
                  _pid(getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer
                    << "[" << _current_time << "]"
                    << "[" << Level_to_string(_level) << "]"
                    << '[' << _pid << "]"
                    << '[' << _filename << "]"
                    << '[' << _line << "]";

                _loginfo = ssbuffer.str();
            }

            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }
            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->Synclog(_loginfo);
                }
            }

        private:
            std::string _current_time; // 当前日志时间
            LogLevel _level;           // 日志等级
            pid_t _pid;                // 进程pid
            std::string _filename;     // 源文件名称
            uint32_t _line;            // 日志所在行号
            Logger &_logger;           // 根据不同的情况作刷新
            std::string _loginfo;      // 一条完整的日志记录
        };

        LogMessage operator()(LogLevel level, const std::string &filename, uint32_t line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy; // 日志刷新的策略
    };

    Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog();
#define ENABLE_FILE_LOG() logger.EnableFileLog();

}